/*
 * @Author: wangmyng wangmyng@163.com
 * @Date: 2025-10-28 22:00:53
 * @LastEditors: wangmyng wangmyng@163.com
 * @LastEditTime: 2025-11-09 23:16:04
 */
import type { ReactNode } from "react";
import { useState, useRef } from "react";
import "./index.less";
import { LoadingOutlined } from "@ant-design/icons";
import { Spin } from "antd";

interface DashboardCardProps {
  titles: string[];
  collapsed?: boolean;
  children: ReactNode | ReactNode[];
  onTitleChange?: (index: number, value?: string) => void;
  loading?: boolean;
  onClose?: () => void;
  showCloseButton?: boolean;
}

/**
 * 通用卡片背景组件
 */
const DashboardCard: React.FC<DashboardCardProps> = ({ titles = [], children = [], collapsed = false, onTitleChange, loading = false, onClose, showCloseButton = false }) => {
  const [isCollapsed, setIsCollapsed] = useState(collapsed);
  const [activeIndex, setActiveIndex] = useState(0);
  const titleContainerRef = useRef<HTMLDivElement>(null);

  const toggleCollapse = () => {
    setIsCollapsed(!isCollapsed);
  };

  const handleTitleClick = (index: number) => {
    setActiveIndex(index);
    onTitleChange?.(index, titles[index] || "");
  };

  const handleWheel = (e: React.WheelEvent<HTMLDivElement>) => {
    e.preventDefault();
    if (titleContainerRef.current) {
      titleContainerRef.current.scrollLeft += e.deltaY;
    }
  };

  return (
    <div className={`dashboard-card ${isCollapsed ? "collapsed" : ""}`}>
      <div className="card-header">
        <div className="panel-icon" />
        <div className="title-scroll-container">
          <div className="title-container" ref={titleContainerRef} onWheel={handleWheel}>
            {(titles || []).map((title, index) => (
              <div key={index} className={`tab-title ${index === activeIndex ? "active" : ""}`} onClick={() => handleTitleClick(index)}>
                {title}
              </div>
            ))}
          </div>
        </div
        >

        {showCloseButton ? (
          <div className="close-btn" onClick={onClose}>
            ×
          </div>
        ) : (
          <span className={`collapse-btn ${isCollapsed ? "collapsed" : ""}`} onClick={toggleCollapse}>
            <div className="collapse-icon" />
          </span>
        )}
      </div>

      {!isCollapsed && (
        <div className="card-content">
          {Array.isArray(children) ? children[activeIndex] || null : children}

          <div className={`loading-container ${loading ? "" : "hidden"}`}>
            <Spin spinning={loading} indicator={<LoadingOutlined className="loading-icon" spin />} />
          </div>
        </div>
      )}
    </div>
  );
};

export default DashboardCard;
